package com.example.work.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    /**
     * 32位小写加密
     * @param str
     * @return
     */
    public static String getmd32(String str){
        try {
            // 获得MD5 消息摘要
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 获得指定编码的字节数据
            byte[] sourceBytes = str.getBytes("UTF-8");
            // 指定的字节数组对摘要执行最终更新
            byte[] digestBytes = messageDigest.digest(sourceBytes);
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < digestBytes.length; i++) {
                int val = (digestBytes[i] & 0xff);
                if (val < 16){
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;// 获得MD5 消息摘要异常
        } catch (UnsupportedEncodingException e) {
            return null;// 获得指定编码的字节数据异常
        }
    }

    /**
     * 16位小写加密
     * @param str
     * @return
     */
    public static String getmd16(String str){ return getmd32(str).substring(8, 24); }
}
